package com.hnkywl.sts.util;

import net.ruixin.utils.CollectionUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * json拼成
 * Created with IntelliJ IDEA.
 * User: jerry
 * Date: 13-3-2
 * Time: 下午3:46
 * To change this template use File | Settings | File Templates.
 */
public class BaseUtils {
    /**
     * 方法名:     fetchCollectionToJson
     * 功能描述:   根据传进的列表以及属性名称生成json串
     * 输入参数:   @param collection 传入的列表
     * otherParam 其他要加入Json的属性，若属性中存在list则key应该为"list_"+属性名
     * propertyNames 属性名称
     * symbol 符号替换
     * 异常:      <RuntimeException  Exception>
     * 创建人:     ccr
     * 创建日期:   13-2-21 上午9:25
     * 修改人:     ccr
     * 修改日期:   13-2-21 上午9:25
     */
    public static String fetchCollectionToJson(String symbol, boolean addClass, Collection collection, Map<String, Object> otherParam, String... propertyNames) {
        String replaceSymbol = ".";
        if (StringUtils.isNotEmpty(symbol))
            replaceSymbol = symbol;
        try {
            String nodes = "";
            StringBuffer json = new StringBuffer();
            if (collection != null) {
                for (Iterator i$ = collection.iterator(); i$.hasNext(); ) {
                    Object obj = i$.next();
                    obj.getClass().getName();
                    json.append("{");
                    for (int i = 0; i < propertyNames.length; i++) {
                        Object property = propertyNames[i].indexOf(".") >= 0
                                && PropertyUtils.getProperty(obj, propertyNames[i].substring(0, propertyNames[i].indexOf("."))) == null ?
                                null : propertyNames[i].lastIndexOf(".") >= 0 && PropertyUtils.getProperty(obj, propertyNames[i].substring(0, propertyNames[i].lastIndexOf("."))) == null ? null : PropertyUtils.getProperty(obj, propertyNames[i]);
                        json.append("\"" + propertyNames[i].replace(".", replaceSymbol) + "\":");
                        if (property instanceof Date) {
                            json.append("\"" + new SimpleDateFormat("yyyy-MM-dd").format(property) + "\",");
                            json.append("\"" + (propertyNames[i] + "_time").replace(".", replaceSymbol) + "\":");
                            json.append("\"" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(property) + "\",");
                        } else if (property instanceof Boolean) {
                            json.append("\"" + ((Boolean) property ? "是" : "否") + "\",");
                        } else if (property instanceof List) {
                            json.append("\"" + CollectionUtils.fetchPropertyToString((List) property, otherParam.get("list_" + propertyNames[i]).toString(), ",") + "\",");
                            json.append("\"" + propertyNames[i].replace(".", replaceSymbol) + "_id\":");
                            json.append("\"" + CollectionUtils.fetchPropertyToString((List) property, "id", ",") + "\",");
                        } else {
                            json.append("\"" + (property == null ? "" : property) + "\",");
                        }
                    }
                    if (otherParam != null && !otherParam.isEmpty()) {
                        Set<String> keySet = otherParam.keySet();
                        for (Iterator<String> i$$ = keySet.iterator(); i$$.hasNext(); ) {
                            String key = i$$.next();
                            if (!key.startsWith("list_")) {
                                json.append("\"" + key.replace(".", replaceSymbol) + "\":");
                                json.append("\"" + otherParam.get(key) + "\",");
                            }
                        }
                    }
                    if (addClass)
                        json.append("\"class\":\"").append(obj.getClass().getSimpleName()).append("\"");
                    else
                        json = new StringBuffer(json.substring(0, json.length() - 1));
                    if (i$.hasNext()) {
                        json.append("},");
                    } else {
                        json.append("}");
                    }
                }
                nodes += json.toString();
            }
            return nodes;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 方法名:     fetchCollectionToJson
     * 功能描述:   根据传进的列表以及属性名称生成json串
     * 输入参数:   @param collection 传入的列表
     * otherParam 其他要加入Json的属性，若属性中存在list则key应该为"list_"+属性名
     * propertyNames 属性名称
     * 异常:      <RuntimeException  Exception>
     * 创建人:     ccr
     * 创建日期:   13-2-21 上午9:25
     * 修改人:     ccr
     * 修改日期:   13-2-21 上午9:25
     */
    public static String fetchCollectionToJson(Collection collection, Map<String, Object> otherParam, String... propertyNames) {
        return fetchCollectionToJson("_", true, collection, otherParam, propertyNames);
    }

    //重载
    public static String fetchCollectionToJson(String symbol, boolean addClass, Collection collection, String... propertyNames) {
        return fetchCollectionToJson(symbol, addClass, collection, null, propertyNames);
    }

    //重载
    public static String fetchCollectionToJson(Collection collection, String... propertyNames) {
        return fetchCollectionToJson("_", true, collection, null, propertyNames);
    }

    /**
     * 方法名:     getTreeJson
     * 功能描述:   生成树Json
     * 输入参数:   @param obj 根节点
     * treeParam 包括text、expand、class、childre、hasChildren和其他属性
     * otherParam 其他参数
     * 创建人:     ccr
     * 创建日期:   13-3-9 下午14:45
     * 修改人:     ccr
     * 修改日期:   13-3-9 下午14:45
     */
    public static String getTreeJson(Object obj, Map<String, String> treeParam, Map<String, Object> otherParam) {
        try {
            StringBuffer json = new StringBuffer();
            if (treeParam != null && !treeParam.isEmpty()) {
                json.append("{");
                Set<String> keySet = treeParam.keySet();
                for (Iterator<String> i$$ = keySet.iterator(); i$$.hasNext(); ) {

                    String key = i$$.next();
                    if ("text".equals(key)) {
                        json.append("\"text\":");
                        json.append("\"" + PropertyUtils.getProperty(obj, treeParam.get(key)) + "\",");
                    } else if ("expand".equals(key)) {
                        json.append("\"expand\":");
                        json.append(("true".equals(treeParam.get(key)) ? true : false) + ",");
                    } else if ("classes".equals(key)) {
                        json.append("\"classes\":");
                        json.append("\"" + treeParam.get(key) + "\",");
                    } else if ("hasChildren".equals(key)) {
                        json.append("\"hasChildren\":");
                        json.append(("true".equals(treeParam.get(key)) ? true : false) + ",");
                    } else if (key.contains("iconCls")) {
                        if (obj.getClass().getSimpleName().equals(key.split("-")[0]))
                            json.append("\"iconCls\":\"").append(treeParam.get(key)).append("\",");
                    } else if ("children".equals(key)) {
                        json.append("\"children\":");
                        json.append(getTreeJson((Collection) PropertyUtils.getProperty(obj, treeParam.get(key)), treeParam, otherParam));
                        json.append(",");
                    } else {
                        json.append("\"" + key + "\":");
                        //json.append("\""+ PropertyUtils.getProperty(obj,treeParam.get(key)) +"\",");
                        json.append("\"" +
                                (treeParam.get(key).indexOf(".") >= 0 && PropertyUtils.getProperty(obj, treeParam.get(key).substring(0, treeParam.get(key).indexOf("."))) == null ? null : PropertyUtils.getProperty(obj, treeParam.get(key)))
                                + "\",");
                    }
                }
            }
            if (otherParam != null && !otherParam.isEmpty()) {
                Set<String> otherParamKeySet = otherParam.keySet();
                for (Iterator<String> i$$ = otherParamKeySet.iterator(); i$$.hasNext(); ) {
                    String key = i$$.next();
                    json.append("\"" + key + "\":");
                    json.append("\"" + otherParam.get(key) + "\",");
                }
            }
            json.deleteCharAt(json.length() - 1).append("}");
            return json.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 方法名:     getTreeJson
     * 功能描述:   生成树Json
     * 输入参数:   @param collection 所有根节点
     * treeParam 包括text、expand、class、childre、hasChildren和其他属性
     * otherParam 其他参数
     * 创建人:     ccr
     * 创建日期:   13-3-9 下午14:45
     * 修改人:     ccr
     * 修改日期:   13-3-9 下午14:45
     */
    public static String getTreeJson(Collection collection, Map<String, String> treeParam, Map<String, Object> otherParam) {
        StringBuffer json = new StringBuffer();
        if (collection != null && !collection.isEmpty()) {
            json.append("[");
            for (Iterator i$ = collection.iterator(); i$.hasNext(); ) {
                Object obj = i$.next();
                json.append(getTreeJson(obj, treeParam, otherParam));
                json.append(",");
            }
            json.deleteCharAt(json.length() - 1).append("]");
            return json.toString();
        } else {
            return "[]";
        }
    }

    //重载
    public static String getTreeJson(Object obj, Map<String, String> treeParam) {
        return getTreeJson(obj, treeParam, null);
    }

    //重载
    public static String getTreeJson(Collection collection, Map<String, String> treeParam) {
        return getTreeJson(collection, treeParam, null);
    }

}
